package com.kira.scaffoldmvc.Dubbo.Compression.Strategy;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import com.github.luben.zstd.Zstd;
import com.github.luben.zstd.ZstdException;

/**
 * Zstd压缩算法实现类
 * 基于Zstd-Java库实现，提供高性能的压缩和解压功能
 */
@Slf4j
public class ZstdCompression implements CompressionStrategy {

    
    // 压缩级别：1-22（值越高压缩率越好但速度越慢，默认3）
    private static final int COMPRESS_LEVEL = 3;

    /**
     * 将字符串压缩为字节数组
     * @param data 待压缩的字符串
     * @return 压缩后的字节数组
     */
    @Override
    public byte[] compress(String data) {
        if (data == null || data.isEmpty()) {
            log.warn("待压缩字符串为空，返回空数组");
            return new byte[0];
        }
        
        try {
            // 将字符串转为UTF-8字节数组
            byte[] input = data.getBytes(StandardCharsets.UTF_8);
            // 使用Zstd压缩，指定压缩级别
            return Zstd.compress(input, COMPRESS_LEVEL);
        } catch (ZstdException e) {
            log.error("Zstd压缩失败", e);
            throw new RuntimeException("Zstd compression failed", e);
        }
    }

    /**
     * 将字节数组解压为字符串
     * @param data 待解压的字节数组
     * @return 解压后的字符串
     */
    @Override
    public String uncompress(byte[] data) {
        if (data == null || data.length == 0) {
            log.warn("待解压字节数组为空，返回空字符串");
            return "";
        }
        
        try {
            // 解压字节数组
            byte[] output = Zstd.decompress(data, (int) Zstd.decompressedSize(data));
            // 将字节数组转为UTF-8字符串
            return new String(output, StandardCharsets.UTF_8);
        } catch (ZstdException e) {
            log.error("Zstd解压失败", e);
            throw new RuntimeException("Zstd decompression failed", e);
        }
    }
}
    